package com.megvii.koala.tv.activity;

import android.app.ActivityManager;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;

import com.megvii.corelib.base.MegviiFragment;
import com.megvii.corelib.components.BaseNetworkErrorView;
import com.megvii.corelib.util.ScreenUtil;
import com.megvii.koala.base.KoalaFragment;
import com.megvii.koala.tv.R;
import com.megvii.koala.tv.fragment.BaseFragment;
import com.megvii.koala.tv.fragment.WebFragment;
import com.megvii.koala.tv.presenter.MainPresenter;
import com.megvii.koala.tv.view.TVErrorView;

import java.util.Stack;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * Created by linyue on 16/1/22.
 */
public class MainActivity extends BaseActivity {

    private Handler record = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message message) {
            recordMemInfo();
            record.sendEmptyMessageDelayed(0, 30000);
            return false;
        }
    });

    @Bind(R.id.main_error)
    protected TVErrorView errorView;

    private FragmentManager fragmentManager;

    private Stack<MegviiFragment> fragmentStack;

    private WebFragment webFragment;

    private MainActivityListener listener;

    private boolean showMenu = true;

    @OnClick(R.id.main_fragment_container)
    public void rl_Main_click(View view) {
        if (showMenu && listener != null) {
            showMenu = false;
            listener.onClickMenuKey();
        } else {
            showMenu = true;
            finishFragments();
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_layout);
        fragmentManager = getFragmentManager();
        fragmentStack = new Stack<>();
        webFragment = (WebFragment) fragmentManager.findFragmentById(R.id.fragment_web);
        ScreenUtil.getInstance().init(this);
        record.sendEmptyMessage(0);
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.e("MainActivity", "onPause: ");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    private void recordMemInfo() {
        ActivityManager am = (ActivityManager) this.getSystemService(Context.ACTIVITY_SERVICE);
        ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo();
        am.getMemoryInfo(mi);
    }

    public WebFragment getWebFragment() {
        return webFragment;
    }

    public void showErrorBluetoothDisconnect() {
        errorView.setIconImage(R.drawable.tv_bluetooth_disconnect);
        errorView.setTitleText("未连接蓝牙开关");
        errorView.setInfotext("请检查蓝牙设置，连接蓝牙开关，或联系管理员");
        errorView.setVisibility(View.VISIBLE);
    }

    public void showErrorBluetoothLowBattery() {
        errorView.setIconImage(R.drawable.tv_bluetooth_low_battery);
        errorView.setTitleText("蓝牙开关电量过低");
        errorView.setInfotext("请更换蓝牙开关的电池");
        errorView.setVisibility(View.VISIBLE);
    }

    public void hideError() {
        errorView.setVisibility(View.GONE);
    }

    public void startFragment(Class<? extends KoalaFragment> clazz, Object param) {
        try {
            KoalaFragment fragment = clazz.newInstance();
            if (fragment instanceof BaseFragment) {
                ((BaseFragment) fragment).setParam(param);
            }
            FragmentTransaction transaction = fragmentManager.beginTransaction();
            transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
            transaction.replace(R.id.main_fragment_container, fragment);
            if (fragmentStack.size() == 1) {
                transaction.hide(webFragment);
            }
            transaction.commit();
            fragmentStack.push(fragment);
            //
            if (listener != null) {
                listener.onFragmentStackChanged();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void finishFragments() {
        if (fragmentStack.isEmpty()) {
            return;
        }
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
        while (!fragmentStack.isEmpty()) {
            MegviiFragment fragment = fragmentStack.pop();
            transaction.remove(fragment);
        }
        transaction.show(webFragment);
        transaction.commit();
        //
        if (listener != null) {
            listener.onFragmentStackChanged();
        }
    }

    public void finishOneFragment() {
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        MegviiFragment fragment = fragmentStack.pop();
        transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
        transaction.remove(fragment);
        transaction.commit();
        if (!fragmentStack.isEmpty()) {
            fragment = fragmentStack.peek();
            transaction = fragmentManager.beginTransaction();
            transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
            if (fragmentStack.size() == 1) {
                transaction.show(webFragment);
            }
            transaction.replace(R.id.main_fragment_container, fragment);
            transaction.commit();
        }
        //
        if (listener != null) {
            listener.onFragmentStackChanged();
        }
    }

    public int getFragmentStackSize() {
        return fragmentStack.size();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        int size = fragmentStack.size();
        if (size > 0) {

            MegviiFragment fragment = fragmentStack.peek();
            return fragment.onKeyDown(keyCode, event);
        } else {
            switch (keyCode) {
                case KeyEvent.KEYCODE_MENU:
                    if (listener != null) {
                        listener.onClickMenuKey();
                    }
                    return true;
            }
            return super.onKeyDown(keyCode, event);
        }
    }

    @Override
    public Class getPresenterClass() {
        return MainPresenter.class;
    }

    @Override
    public BaseNetworkErrorView getNetworkErrorView() {
        return null;
    }

    public void setListener(MainActivityListener listener) {
        this.listener = listener;
    }

    public interface MainActivityListener {
        public void onClickMenuKey();

        public void onFragmentStackChanged();
    }
}
